import cv2
import mediapipe as mp

# 初始化 Mediapipe 的人体关键点检测模块
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()

# 打开摄像头
cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 将图像转换为 RGB 格式
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # 进行人体关键点检测
    results = pose.process(rgb_frame)

    if results.pose_landmarks:
        # 获取左右手腕的关键点坐标
        left_wrist = results.pose_landmarks.landmark[mp_pose.PoseLandmark.LEFT_WRIST]
        right_wrist = results.pose_landmarks.landmark[mp_pose.PoseLandmark.RIGHT_WRIST]

        # 获取图像宽度
        image_width = frame.shape[1]

        # 判断手腕位置
        if left_wrist.x * image_width < image_width / 2:
            left_wrist_position = "Left"
        else:
            left_wrist_position = "Right"

        if right_wrist.x * image_width < image_width / 2:
            right_wrist_position = "Left"
        else:
            right_wrist_position = "Right"

        # 在图像上显示手腕位置信息
        cv2.putText(frame, f"Left Wrist: {left_wrist_position}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        cv2.putText(frame, f"Right Wrist: {right_wrist_position}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    # 显示处理后的图像
    cv2.imshow('Wrist Position Detection', frame)

    # 按 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
